package com.lk.car.service.impl;

import com.lk.basic.service.IBaiduAuditService;
import com.lk.basic.util.AjaxResult;
import com.lk.basic.util.LoginContext;
import com.lk.basic.util.VelocityUtils;
import com.lk.car.domain.Car;
import com.lk.car.domain.CarDetail;
import com.lk.car.domain.CarOnlineAuditLog;
import com.lk.car.domain.CarType;
import com.lk.car.es.doc.CarDoc;
import com.lk.car.es.repository.CarDocRepository;
import com.lk.car.mapper.CarDetailMapper;
import com.lk.car.mapper.CarMapper;
import com.lk.car.mapper.CarOnlineAuditLogMapper;
import com.lk.car.mapper.CarTypeMapper;
import com.lk.car.service.ICarService;
import com.lk.basic.service.impl.BaseServiceImpl;

import com.lk.org.domain.Employee;
import com.lk.org.domain.Shop;
import com.lk.org.mapper.ShopMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.lang.model.element.VariableElement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lk
 * @since 2022-11-04
 */
@Service
public class CarServiceImpl extends BaseServiceImpl<Car> implements ICarService {

    @Value("${velocity.tempaltePath}")
    private String tempaltePath;

    @Value("${velocity.targetPath}")
    private String targetPath;

    @Autowired
    private CarDetailMapper carDetailMapper;

    @Autowired
    private IBaiduAuditService baiduAuditService;

    @Autowired
    private CarOnlineAuditLogMapper carOnlineAuditLogMapper;

    @Autowired
    private CarMapper carMapper;

    @Autowired
    private CarDocRepository carDocRepository;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private CarTypeMapper carTypeMapper;

    @Transactional
    @Override
    public void insert(Car car) {
        CarDetail carDetail=car.getCarDetail();
        String text=car.getTitle()+""+carDetail.getInfo();
        AjaxResult result = baiduAuditService.audit(text, car.getCover(), null);
        CarOnlineAuditLog log=new CarOnlineAuditLog();
        log.setAuditTime(new Date());
        if (result.getSuccess()){
            //审核通过
            log.setState(1);
            log.setNote("自动审核通过");
        }else {
            //审核失败
            log.setState(2);
            log.setNote("自动审核失败,失败原因："+result.getMessage());
        }
        //设置添加时间
        car.setCreatetime(new Date());
        //设置状态
        car.setState(0);
        //设置审核状态
        car.setAuditstate(0);
        //设置店铺信息
        Employee loginAdmin = LoginContext.getLoginAdmin();
        car.setShopId(loginAdmin.getShop().getId());
        car.setShopname(loginAdmin.getShop().getName());
        //设置销售人员信息
        car.setSellerId(loginAdmin.getId());
        super.insert(car);
        //保存carDetail的信息
        //CarDetail carDetail = car.getCarDetail();
        carDetail.setCarId(car.getId());
        carDetail.setCartitle(car.getTitle());
        carDetailMapper.insert(carDetail);


        //调用百度Ai
        //String text=car.getTitle()+""+carDetail.getInfo();

        //AjaxResult result = baiduAuditService.audit(text, car.getCover(), null);

        //添加审核日志
//        CarOnlineAuditLog log=new CarOnlineAuditLog();
//        log.setCarId(car.getId());
//        log.setAuditTime(new Date());

        log.setCarId(car.getId());
        carOnlineAuditLogMapper.insert(log);

//        car.setAuditstate(log.getState());
//        super.update(car);
    }


    @Override
    public void onsale(List<Long> ids) throws Exception  {
        //参数校验
        if (ids==null || ids.size()==0){
            throw new RuntimeException("尴尬了");
        }
        int count=carMapper.getAuditPassCount(ids);
        if (count<ids.size()){
            throw  new RuntimeException("尬中尬");
        }

        //将数据添加到ES
        List<CarDoc> docs=buildEsCarDocObj(ids);
        carDocRepository.saveAll(docs);
        //修改数据库状态
        carMapper.onsale(ids);

        //记录日志
        addAuditLog(ids,3);

        staticPage(ids);

    }
    @Override
    public void offsale(List<Long> ids) {
        if (ids==null || ids.size()==0){
            throw new RuntimeException("尴尬了");
        }
        List<CarDoc> docs=new ArrayList<>();
        for (Long id : ids) {
            CarDoc doc=new CarDoc();
            doc.setId(id);
            docs.add(doc);

        }
        carDocRepository.deleteAll(docs);
        carMapper.offsale(ids);

        addAuditLog(ids,4);
    }

    private void staticPage(List<Long> ids) throws Exception {

        for (Long id : ids) {
            //每次循环都调用VelocityUtils方法生成静态页面
            //数据对象
            Car car=carMapper.selById(id);
            String targetPath=this.targetPath+id+".html";
                    VelocityUtils.staticByTemplate(car,tempaltePath,targetPath);
        }
    }

    private List<CarDoc> buildEsCarDocObj(List<Long> ids) {
       /* List<CarDoc> result = new ArrayList<>();
        ids.forEach(carId->{
            result.add(buildCarDoc(carId));
        });
        return result;*/
        List<CarDoc> docs=new ArrayList<>();
        List<Car> cars=carMapper.getCarDetailByIds(ids);
        for (Car car : cars) {
            CarDoc doc=new CarDoc();
            BeanUtils.copyProperties(car,doc);
            Shop shop=car.getShop();
            if (Objects.nonNull(shop)){
                doc.setShopId(shop.getId());
                doc.setShopName(shop.getName());
                doc.setShopAddress(shop.getAddress());
            }
            CarType type=car.getType();
            if (Objects.nonNull(type)){
                doc.setTypeId(type.getId());
                doc.setTypeName(type.getName());
            }
            CarDetail carDetail=car.getCarDetail();
            if (Objects.nonNull(carDetail)){
                doc.setCarInfo(carDetail.getInfo());
            }
            docs.add(doc);
        }
        return docs;
    }
    /*private CarDoc buildCarDoc(Long carId) {
        Car car=carMapper.selById(carId);
        //Car car = carMapper.loadById(carId);//数据库
        CarDoc carDoc = new CarDoc();//es
        carDoc.setId(carId);
        carDoc.setTitle(car.getTitle());
        carDoc.setCover(car.getCover());
        carDoc.setSaleprice(car.getSaleprice());
        carDoc.setCostprice(car.getCostprice());
        carDoc.setIsnew(car.getIsnew());
        carDoc.setReigstertime(car.getReigstertime());
        carDoc.setMileage(car.getMileage());
        Shop shop = shopMapper.selById(car.getShopId());
        //Shop shop = shopMapper.loadById(car.getShopId());
        carDoc.setShopId(shop.getId());
        carDoc.setShopName(shop.getName());
        carDoc.setShopAdress(shop.getAddress());
        carDoc.setOnsaletime(car.getOnsaletime());
        carDoc.setCosteffective(car.getCosteffective());
        carDoc.setRushsale(car.getRushsale());
        carDoc.setQuasinewcar(car.getQuasinewcar());
        carDoc.setTransitivecountry(car.getTransitivecountry());
        CarType carType = carTypeMapper.selById(car.getTypeId());
        carDoc.setTypeId(carType.getId());
        carDoc.setTypeName(carType.getName());
        CarDetail detail = carDetailMapper.selById(carId);
        if (detail!=null)
            carDoc.setCarInfo(detail.getInfo());
        return carDoc;
    }*/

    private void addAuditLog(List<Long> ids,Integer state) {
        Employee loginAdmin=LoginContext.getLoginAdmin();
        String note=state==3?"上架":"下架";
        ArrayList<CarOnlineAuditLog> logs = new ArrayList<>();
        for (Long id : ids) {
            CarOnlineAuditLog log = new CarOnlineAuditLog();
            log.setCarId(id);
            log.setNote(loginAdmin.getUsername()+"对id"+id+"上架");
            log.setState(state);
            log.setAuditTime(new Date());
            log.setAuditId(loginAdmin.getId());
            logs.add(log);
        }
        carOnlineAuditLogMapper.batchInsert(logs);
    }


}
